1 /*
2 * Copyright (C) 2007 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.common.collect;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20 import static com.google.common.base.Preconditions.checkElementIndex;
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Preconditions.checkPositionIndex;
23 import static com.google.common.base.Preconditions.checkPositionIndexes;
24 import static com.google.common.base.Preconditions.checkState;
25 import static com.google.common.collect.CollectPreconditions.checkNonnegative;
26 import static com.google.common.collect.CollectPreconditions.checkRemove;
27
28 import com.google.common.annotations.Beta;
29 import com.google.common.annotations.GwtCompatible;
30 import com.google.common.annotations.GwtIncompatible;
31 import com.google.common.annotations.VisibleForTesting;
32 import com.google.common.base.Function;
33 import com.google.common.base.Objects;
34 import com.google.common.math.IntMath;
35 import com.google.common.primitives.Ints;
36
37 import java.io.Serializable;
38 import java.math.RoundingMode;
39 import java.util.AbstractList;
40 import java.util.AbstractSequentialList;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Collection;
44 import java.util.Collections;
45 import java.util.Iterator;
46 import java.util.LinkedList;
47 import java.util.List;
48 import java.util.ListIterator;
49 import java.util.NoSuchElementException;
50 import java.util.RandomAccess;
51 import java.util.concurrent.CopyOnWriteArrayList;
52
53 import javax.annotation.Nullable;
54
55 /**
56 * Static utility methods pertaining to {@link List} instances. Also see this
57 * class's counterparts {@link Sets}, {@link Maps} and {@link Queues}.
58 *
59 * <p>See the Guava User Guide article on <a href=
60 * "http://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained#Lists">
61 * {@code Lists}</a>.
62 *
63 * @author Kevin Bourrillion
64 * @author Mike Bostock
65 * @author Louis Wasserman
66 * @since 2.0 (imported from Google Collections Library)
67 */
68 @GwtCompatible(emulated = true)
69 public final class Lists {
70 private Lists() {}
71
72 // ArrayList
73
74 /**
75 * Creates a <i>mutable</i>, empty {@code ArrayList} instance (for Java 6 and
76 * earlier).
77 *
78 * <p><b>Note:</b> if mutability is not required, use {@link
79 * ImmutableList#of()} instead.
80 *
81 * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and
82 * should be treated as deprecated. Instead, use the {@code ArrayList}
83 * {@linkplain ArrayList#ArrayList() constructor} directly, taking advantage
84 * of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
85 */
86 @GwtCompatible(serializable = true)
87 public static <E> ArrayList<E> newArrayList() {
88 return new ArrayList<E>();
89 }
90
91 /**
92 * Creates a <i>mutable</i> {@code ArrayList} instance containing the given
93 * elements.
94 *
95 * <p><b>Note:</b> essentially the only reason to use this method is when you
96 * will need to add or remove elements later. Otherwise, for non-null elements
97 * use {@link ImmutableList#of()} (for varargs) or {@link
98 * ImmutableList#copyOf(Object[])} (for an array) instead. If any elements
99 * might be null, or you need support for {@link List#set(int, Object)}, use
100 * {@link Arrays#asList}.
101 *
102 * <p>Note that even when you do need the ability to add or remove, this method
103 * provides only a tiny bit of syntactic sugar for {@code newArrayList(}{@link
104 * Arrays#asList asList}{@code (...))}, or for creating an empty list then
105 * calling {@link Collections#addAll}. This method is not actually very useful
106 * and will likely be deprecated in the future.
107 */
108 @GwtCompatible(serializable = true)
109 public static <E> ArrayList<E> newArrayList(E... elements) {
110 checkNotNull(elements); // for GWT
111 // Avoid integer overflow when a large array is passed in
112 int capacity = computeArrayListCapacity(elements.length);
113 ArrayList<E> list = new ArrayList<E>(capacity);
114 Collections.addAll(list, elements);
115 return list;
116 }
117
118 @VisibleForTesting static int computeArrayListCapacity(int arraySize) {
119 checkNonnegative(arraySize, "arraySize");
120
121 // TODO(kevinb): Figure out the right behavior, and document it
122 return Ints.saturatedCast(5L + arraySize + (arraySize / 10));
123 }
124
125 /**
126 * Creates a <i>mutable</i> {@code ArrayList} instance containing the given
127 * elements; a very thin shortcut for creating an empty list then calling
128 * {@link Iterables#addAll}.
129 *
130 * <p><b>Note:</b> if mutability is not required and the elements are
131 * non-null, use {@link ImmutableList#copyOf(Iterable)} instead. (Or, change
132 * {@code elements} to be a {@link FluentIterable} and call
133 * {@code elements.toList()}.)
134 *
135 * <p><b>Note for Java 7 and later:</b> if {@code elements} is a {@link
136 * Collection}, you don't need this method. Use the {@code ArrayList}
137 * {@linkplain ArrayList#ArrayList(Collection) constructor} directly, taking
138 * advantage of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
139 */
140 @GwtCompatible(serializable = true)
141 public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
142 checkNotNull(elements); // for GWT
143 // Let ArrayList's sizing logic work, if possible
144 return (elements instanceof Collection)
145 ? new ArrayList<E>(Collections2.cast(elements))
146 : newArrayList(elements.iterator());
147 }
148
149 /**
150 * Creates a <i>mutable</i> {@code ArrayList} instance containing the given
151 * elements; a very thin shortcut for creating an empty list and then calling
152 * {@link Iterators#addAll}.
153 *
154 * <p><b>Note:</b> if mutability is not required and the elements are
155 * non-null, use {@link ImmutableList#copyOf(Iterator)} instead.
156 */
157 @GwtCompatible(serializable = true)
158 public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
159 ArrayList<E> list = newArrayList();
160 Iterators.addAll(list, elements);
161 return list;
162 }
163
164 /**
165 * Creates an {@code ArrayList} instance backed by an array with the specified
166 * initial size; simply delegates to {@link ArrayList#ArrayList(int)}.
167 *
168 * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and
169 * should be treated as deprecated. Instead, use {@code new }{@link
170 * ArrayList#ArrayList(int) ArrayList}{@code <>(int)} directly, taking
171 * advantage of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
172 * (Unlike here, there is no risk of overload ambiguity, since the {@code
173 * ArrayList} constructors very wisely did not accept varargs.)
174 *
175 * @param initialArraySize the exact size of the initial backing array for
176 * the returned array list ({@code ArrayList} documentation calls this
177 * value the "capacity")
178 * @return a new, empty {@code ArrayList} which is guaranteed not to resize
179 * itself unless its size reaches {@code initialArraySize + 1}
180 * @throws IllegalArgumentException if {@code initialArraySize} is negative
181 */
182 @GwtCompatible(serializable = true)
183 public static <E> ArrayList<E> newArrayListWithCapacity(
184 int initialArraySize) {
185 checkNonnegative(initialArraySize, "initialArraySize"); // for GWT.
186 return new ArrayList<E>(initialArraySize);
187 }
188
189 /**
190 * Creates an {@code ArrayList} instance to hold {@code estimatedSize}
191 * elements, <i>plus</i> an unspecified amount of padding; you almost
192 * certainly mean to call {@link #newArrayListWithCapacity} (see that method
193 * for further advice on usage).
194 *
195 * <p><b>Note:</b> This method will soon be deprecated. Even in the rare case
196 * that you do want some amount of padding, it's best if you choose your
197 * desired amount explicitly.
198 *
199 * @param estimatedSize an estimate of the eventual {@link List#size()} of
200 * the new list
201 * @return a new, empty {@code ArrayList}, sized appropriately to hold the
202 * estimated number of elements
203 * @throws IllegalArgumentException if {@code estimatedSize} is negative
204 */
205 @GwtCompatible(serializable = true)
206 public static <E> ArrayList<E> newArrayListWithExpectedSize(
207 int estimatedSize) {
208 return new ArrayList<E>(computeArrayListCapacity(estimatedSize));
209 }
210
211 // LinkedList
212
213 /**
214 * Creates a <i>mutable</i>, empty {@code LinkedList} instance (for Java 6 and
215 * earlier).
216 *
217 * <p><b>Note:</b> if you won't be adding any elements to the list, use {@link
218 * ImmutableList#of()} instead.
219 *
220 * <p><b>Performance note:</b> {@link ArrayList} and {@link
221 * java.util.ArrayDeque} consistently outperform {@code LinkedList} except in
222 * certain rare and specific situations. Unless you have spent a lot of time
223 * benchmarking your specific needs, use one of those instead.
224 *
225 * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and
226 * should be treated as deprecated. Instead, use the {@code LinkedList}
227 * {@linkplain LinkedList#LinkedList() constructor} directly, taking advantage
228 * of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
229 */
230 @GwtCompatible(serializable = true)
231 public static <E> LinkedList<E> newLinkedList() {
232 return new LinkedList<E>();
233 }
234
235 /**
236 * Creates a <i>mutable</i> {@code LinkedList} instance containing the given
237 * elements; a very thin shortcut for creating an empty list then calling
238 * {@link Iterables#addAll}.
239 *
240 * <p><b>Note:</b> if mutability is not required and the elements are
241 * non-null, use {@link ImmutableList#copyOf(Iterable)} instead. (Or, change
242 * {@code elements} to be a {@link FluentIterable} and call
243 * {@code elements.toList()}.)
244 *
245 * <p><b>Performance note:</b> {@link ArrayList} and {@link
246 * java.util.ArrayDeque} consistently outperform {@code LinkedList} except in
247 * certain rare and specific situations. Unless you have spent a lot of time
248 * benchmarking your specific needs, use one of those instead.
249 *
250 * <p><b>Note for Java 7 and later:</b> if {@code elements} is a {@link
251 * Collection}, you don't need this method. Use the {@code LinkedList}
252 * {@linkplain LinkedList#LinkedList(Collection) constructor} directly, taking
253 * advantage of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
254 */
255 @GwtCompatible(serializable = true)
256 public static <E> LinkedList<E> newLinkedList(
257 Iterable<? extends E> elements) {
258 LinkedList<E> list = newLinkedList();
259 Iterables.addAll(list, elements);
260 return list;
261 }
262
263 /**
264 * Creates an empty {@code CopyOnWriteArrayList} instance.
265 *
266 * <p><b>Note:</b> if you need an immutable empty {@link List}, use
267 * {@link Collections#emptyList} instead.
268 *
269 * @return a new, empty {@code CopyOnWriteArrayList}
270 * @since 12.0
271 */
272 @GwtIncompatible("CopyOnWriteArrayList")
273 public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
274 return new CopyOnWriteArrayList<E>();
275 }
276
277 /**
278 * Creates a {@code CopyOnWriteArrayList} instance containing the given elements.
279 *
280 * @param elements the elements that the list should contain, in order
281 * @return a new {@code CopyOnWriteArrayList} containing those elements
282 * @since 12.0
283 */
284 @GwtIncompatible("CopyOnWriteArrayList")
285 public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(
286 Iterable<? extends E> elements) {
287 // We copy elements to an ArrayList first, rather than incurring the
288 // quadratic cost of adding them to the COWAL directly.
289 Collection<? extends E> elementsCollection = (elements instanceof Collection)
290 ? Collections2.cast(elements)
291 : newArrayList(elements);
292 return new CopyOnWriteArrayList<E>(elementsCollection);
293 }
294
295 /**
296 * Returns an unmodifiable list containing the specified first element and
297 * backed by the specified array of additional elements. Changes to the {@code
298 * rest} array will be reflected in the returned list. Unlike {@link
299 * Arrays#asList}, the returned list is unmodifiable.
300 *
301 * <p>This is useful when a varargs method needs to use a signature such as
302 * {@code (Foo firstFoo, Foo... moreFoos)}, in order to avoid overload
303 * ambiguity or to enforce a minimum argument count.
304 *
305 * <p>The returned list is serializable and implements {@link RandomAccess}.
306 *
307 * @param first the first element
308 * @param rest an array of additional elements, possibly empty
309 * @return an unmodifiable list containing the specified elements
310 */
311 public static <E> List<E> asList(@Nullable E first, E[] rest) {
312 return new OnePlusArrayList<E>(first, rest);
313 }
314
315 /** @see Lists#asList(Object, Object[]) */
316 private static class OnePlusArrayList<E> extends AbstractList<E>
317 implements Serializable, RandomAccess {
318 final E first;
319 final E[] rest;
320
321 OnePlusArrayList(@Nullable E first, E[] rest) {
322 this.first = first;
323 this.rest = checkNotNull(rest);
324 }
325 @Override public int size() {
326 return rest.length + 1;
327 }
328 @Override public E get(int index) {
329 // check explicitly so the IOOBE will have the right message
330 checkElementIndex(index, size());
331 return (index == 0) ? first : rest[index - 1];
332 }
333 private static final long serialVersionUID = 0;
334 }
335
336 /**
337 * Returns an unmodifiable list containing the specified first and second
338 * element, and backed by the specified array of additional elements. Changes
339 * to the {@code rest} array will be reflected in the returned list. Unlike
340 * {@link Arrays#asList}, the returned list is unmodifiable.
341 *
342 * <p>This is useful when a varargs method needs to use a signature such as
343 * {@code (Foo firstFoo, Foo secondFoo, Foo... moreFoos)}, in order to avoid
344 * overload ambiguity or to enforce a minimum argument count.
345 *
346 * <p>The returned list is serializable and implements {@link RandomAccess}.
347 *
348 * @param first the first element
349 * @param second the second element
350 * @param rest an array of additional elements, possibly empty
351 * @return an unmodifiable list containing the specified elements
352 */
353 public static <E> List<E> asList(
354 @Nullable E first, @Nullable E second, E[] rest) {
355 return new TwoPlusArrayList<E>(first, second, rest);
356 }
357
358 /** @see Lists#asList(Object, Object, Object[]) */
359 private static class TwoPlusArrayList<E> extends AbstractList<E>
360 implements Serializable, RandomAccess {
361 final E first;
362 final E second;
363 final E[] rest;
364
365 TwoPlusArrayList(@Nullable E first, @Nullable E second, E[] rest) {
366 this.first = first;
367 this.second = second;
368 this.rest = checkNotNull(rest);
369 }
370 @Override public int size() {
371 return rest.length + 2;
372 }
373 @Override public E get(int index) {
374 switch (index) {
375 case 0:
376 return first;
377 case 1:
378 return second;
379 default:
380 // check explicitly so the IOOBE will have the right message
381 checkElementIndex(index, size());
382 return rest[index - 2];
383 }
384 }
385 private static final long serialVersionUID = 0;
386 }
387
388 /**
389 * Returns every possible list that can be formed by choosing one element
390 * from each of the given lists in order; the "n-ary
391 * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
392 * product</a>" of the lists. For example: <pre> {@code
393 *
394 * Lists.cartesianProduct(ImmutableList.of(
395 * ImmutableList.of(1, 2),
396 * ImmutableList.of("A", "B", "C")))}</pre>
397 *
398 * <p>returns a list containing six lists in the following order:
399 *
400 * <ul>
401 * <li>{@code ImmutableList.of(1, "A")}
402 * <li>{@code ImmutableList.of(1, "B")}
403 * <li>{@code ImmutableList.of(1, "C")}
404 * <li>{@code ImmutableList.of(2, "A")}
405 * <li>{@code ImmutableList.of(2, "B")}
406 * <li>{@code ImmutableList.of(2, "C")}
407 * </ul>
408 *
409 * <p>The result is guaranteed to be in the "traditional", lexicographical
410 * order for Cartesian products that you would get from nesting for loops:
411 * <pre> {@code
412 *
413 * for (B b0 : lists.get(0)) {
414 * for (B b1 : lists.get(1)) {
415 * ...
416 * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
417 * // operate on tuple
418 * }
419 * }}</pre>
420 *
421 * <p>Note that if any input list is empty, the Cartesian product will also be
422 * empty. If no lists at all are provided (an empty list), the resulting
423 * Cartesian product has one element, an empty list (counter-intuitive, but
424 * mathematically consistent).
425 *
426 * <p><i>Performance notes:</i> while the cartesian product of lists of size
427 * {@code m, n, p} is a list of size {@code m x n x p}, its actual memory
428 * consumption is much smaller. When the cartesian product is constructed, the
429 * input lists are merely copied. Only as the resulting list is iterated are
430 * the individual lists created, and these are not retained after iteration.
431 *
432 * @param lists the lists to choose elements from, in the order that
433 * the elements chosen from those lists should appear in the resulting
434 * lists
435 * @param <B> any common base class shared by all axes (often just {@link
436 * Object})
437 * @return the Cartesian product, as an immutable list containing immutable
438 * lists
439 * @throws IllegalArgumentException if the size of the cartesian product would
440 * be greater than {@link Integer#MAX_VALUE}
441 * @throws NullPointerException if {@code lists}, any one of the {@code lists},
442 * or any element of a provided list is null
443 */ static <B> List<List<B>>
444 cartesianProduct(List<? extends List<? extends B>> lists) {
445 return CartesianList.create(lists);
446 }
447
448 /**
449 * Returns every possible list that can be formed by choosing one element
450 * from each of the given lists in order; the "n-ary
451 * <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian
452 * product</a>" of the lists. For example: <pre> {@code
453 *
454 * Lists.cartesianProduct(ImmutableList.of(
455 * ImmutableList.of(1, 2),
456 * ImmutableList.of("A", "B", "C")))}</pre>
457 *
458 * <p>returns a list containing six lists in the following order:
459 *
460 * <ul>
461 * <li>{@code ImmutableList.of(1, "A")}
462 * <li>{@code ImmutableList.of(1, "B")}
463 * <li>{@code ImmutableList.of(1, "C")}
464 * <li>{@code ImmutableList.of(2, "A")}
465 * <li>{@code ImmutableList.of(2, "B")}
466 * <li>{@code ImmutableList.of(2, "C")}
467 * </ul>
468 *
469 * <p>The result is guaranteed to be in the "traditional", lexicographical
470 * order for Cartesian products that you would get from nesting for loops:
471 * <pre> {@code
472 *
473 * for (B b0 : lists.get(0)) {
474 * for (B b1 : lists.get(1)) {
475 * ...
476 * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...);
477 * // operate on tuple
478 * }
479 * }}</pre>
480 *
481 * <p>Note that if any input list is empty, the Cartesian product will also be
482 * empty. If no lists at all are provided (an empty list), the resulting
483 * Cartesian product has one element, an empty list (counter-intuitive, but
484 * mathematically consistent).
485 *
486 * <p><i>Performance notes:</i> while the cartesian product of lists of size
487 * {@code m, n, p} is a list of size {@code m x n x p}, its actual memory
488 * consumption is much smaller. When the cartesian product is constructed, the
489 * input lists are merely copied. Only as the resulting list is iterated are
490 * the individual lists created, and these are not retained after iteration.
491 *
492 * @param lists the lists to choose elements from, in the order that
493 * the elements chosen from those lists should appear in the resulting
494 * lists
495 * @param <B> any common base class shared by all axes (often just {@link
496 * Object})
497 * @return the Cartesian product, as an immutable list containing immutable
498 * lists
499 * @throws IllegalArgumentException if the size of the cartesian product would
500 * be greater than {@link Integer#MAX_VALUE}
501 * @throws NullPointerException if {@code lists}, any one of the
502 * {@code lists}, or any element of a provided list is null
503 */ static <B> List<List<B>>
504 cartesianProduct(List<? extends B>... lists) {
505 return cartesianProduct(Arrays.asList(lists));
506 }
507
508 /**
509 * Returns a list that applies {@code function} to each element of {@code
510 * fromList}. The returned list is a transformed view of {@code fromList};
511 * changes to {@code fromList} will be reflected in the returned list and vice
512 * versa.
513 *
514 * <p>Since functions are not reversible, the transform is one-way and new
515 * items cannot be stored in the returned list. The {@code add},
516 * {@code addAll} and {@code set} methods are unsupported in the returned
517 * list.
518 *
519 * <p>The function is applied lazily, invoked when needed. This is necessary
520 * for the returned list to be a view, but it means that the function will be
521 * applied many times for bulk operations like {@link List#contains} and
522 * {@link List#hashCode}. For this to perform well, {@code function} should be
523 * fast. To avoid lazy evaluation when the returned list doesn't need to be a
524 * view, copy the returned list into a new list of your choosing.
525 *
526 * <p>If {@code fromList} implements {@link RandomAccess}, so will the
527 * returned list. The returned list is threadsafe if the supplied list and
528 * function are.
529 *
530 * <p>If only a {@code Collection} or {@code Iterable} input is available, use
531 * {@link Collections2#transform} or {@link Iterables#transform}.
532 *
533 * <p><b>Note:</b> serializing the returned list is implemented by serializing
534 * {@code fromList}, its contents, and {@code function} -- <i>not</i> by
535 * serializing the transformed values. This can lead to surprising behavior,
536 * so serializing the returned list is <b>not recommended</b>. Instead,
537 * copy the list using {@link ImmutableList#copyOf(Collection)} (for example),
538 * then serialize the copy. Other methods similar to this do not implement
539 * serialization at all for this reason.
540 */
541 public static <F, T> List<T> transform(
542 List<F> fromList, Function<? super F, ? extends T> function) {
543 return (fromList instanceof RandomAccess)
544 ? new TransformingRandomAccessList<F, T>(fromList, function)
545 : new TransformingSequentialList<F, T>(fromList, function);
546 }
547
548 /**
549 * Implementation of a sequential transforming list.
550 *
551 * @see Lists#transform
552 */
553 private static class TransformingSequentialList<F, T>
554 extends AbstractSequentialList<T> implements Serializable {
555 final List<F> fromList;
556 final Function<? super F, ? extends T> function;
557
558 TransformingSequentialList(
559 List<F> fromList, Function<? super F, ? extends T> function) {
560 this.fromList = checkNotNull(fromList);
561 this.function = checkNotNull(function);
562 }
563 /**
564 * The default implementation inherited is based on iteration and removal of
565 * each element which can be overkill. That's why we forward this call
566 * directly to the backing list.
567 */
568 @Override public void clear() {
569 fromList.clear();
570 }
571 @Override public int size() {
572 return fromList.size();
573 }
574 @Override public ListIterator<T> listIterator(final int index) {
575 return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
576 @Override
577 T transform(F from) {
578 return function.apply(from);
579 }
580 };
581 }
582
583 private static final long serialVersionUID = 0;
584 }
585
586 /**
587 * Implementation of a transforming random access list. We try to make as many
588 * of these methods pass-through to the source list as possible so that the
589 * performance characteristics of the source list and transformed list are
590 * similar.
591 *
592 * @see Lists#transform
593 */
594 private static class TransformingRandomAccessList<F, T>
595 extends AbstractList<T> implements RandomAccess, Serializable {
596 final List<F> fromList;
597 final Function<? super F, ? extends T> function;
598
599 TransformingRandomAccessList(
600 List<F> fromList, Function<? super F, ? extends T> function) {
601 this.fromList = checkNotNull(fromList);
602 this.function = checkNotNull(function);
603 }
604 @Override public void clear() {
605 fromList.clear();
606 }
607 @Override public T get(int index) {
608 return function.apply(fromList.get(index));
609 }
610 @Override public Iterator<T> iterator() {
611 return listIterator();
612 }
613 @Override public ListIterator<T> listIterator(int index) {
614 return new TransformedListIterator<F, T>(fromList.listIterator(index)) {
615 @Override
616 T transform(F from) {
617 return function.apply(from);
618 }
619 };
620 }
621 @Override public boolean isEmpty() {
622 return fromList.isEmpty();
623 }
624 @Override public T remove(int index) {
625 return function.apply(fromList.remove(index));
626 }
627 @Override public int size() {
628 return fromList.size();
629 }
630 private static final long serialVersionUID = 0;
631 }
632
633 /**
634 * Returns consecutive {@linkplain List#subList(int, int) sublists} of a list,
635 * each of the same size (the final list may be smaller). For example,
636 * partitioning a list containing {@code [a, b, c, d, e]} with a partition
637 * size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing
638 * two inner lists of three and two elements, all in the original order.
639 *
640 * <p>The outer list is unmodifiable, but reflects the latest state of the
641 * source list. The inner lists are sublist views of the original list,
642 * produced on demand using {@link List#subList(int, int)}, and are subject
643 * to all the usual caveats about modification as explained in that API.
644 *
645 * @param list the list to return consecutive sublists of
646 * @param size the desired size of each sublist (the last may be
647 * smaller)
648 * @return a list of consecutive sublists
649 * @throws IllegalArgumentException if {@code partitionSize} is nonpositive
650 */
651 public static <T> List<List<T>> partition(List<T> list, int size) {
652 checkNotNull(list);
653 checkArgument(size > 0);
654 return (list instanceof RandomAccess)
655 ? new RandomAccessPartition<T>(list, size)
656 : new Partition<T>(list, size);
657 }
658
659 private static class Partition<T> extends AbstractList<List<T>> {
660 final List<T> list;
661 final int size;
662
663 Partition(List<T> list, int size) {
664 this.list = list;
665 this.size = size;
666 }
667
668 @Override public List<T> get(int index) {
669 checkElementIndex(index, size());
670 int start = index * size;
671 int end = Math.min(start + size, list.size());
672 return list.subList(start, end);
673 }
674
675 @Override public int size() {
676 return IntMath.divide(list.size(), size, RoundingMode.CEILING);
677 }
678
679 @Override public boolean isEmpty() {
680 return list.isEmpty();
681 }
682 }
683
684 private static class RandomAccessPartition<T> extends Partition<T>
685 implements RandomAccess {
686 RandomAccessPartition(List<T> list, int size) {
687 super(list, size);
688 }
689 }
690
691 /**
692 * Returns a view of the specified string as an immutable list of {@code
693 * Character} values.
694 *
695 * @since 7.0
696 */
697 @Beta public static ImmutableList<Character> charactersOf(String string) {
698 return new StringAsImmutableList(checkNotNull(string));
699 }
700
701 @SuppressWarnings("serial") // serialized using ImmutableList serialization
702 private static final class StringAsImmutableList
703 extends ImmutableList<Character> {
704
705 private final String string;
706
707 StringAsImmutableList(String string) {
708 this.string = string;
709 }
710
711 @Override public int indexOf(@Nullable Object object) {
712 return (object instanceof Character)
713 ? string.indexOf((Character) object) : -1;
714 }
715
716 @Override public int lastIndexOf(@Nullable Object object) {
717 return (object instanceof Character)
718 ? string.lastIndexOf((Character) object) : -1;
719 }
720
721 @Override public ImmutableList<Character> subList(
722 int fromIndex, int toIndex) {
723 checkPositionIndexes(fromIndex, toIndex, size()); // for GWT
724 return charactersOf(string.substring(fromIndex, toIndex));
725 }
726
727 @Override boolean isPartialView() {
728 return false;
729 }
730
731 @Override public Character get(int index) {
732 checkElementIndex(index, size()); // for GWT
733 return string.charAt(index);
734 }
735
736 @Override public int size() {
737 return string.length();
738 }
739 }
740
741 /**
742 * Returns a view of the specified {@code CharSequence} as a {@code
743 * List<Character>}, viewing {@code sequence} as a sequence of Unicode code
744 * units. The view does not support any modification operations, but reflects
745 * any changes to the underlying character sequence.
746 *
747 * @param sequence the character sequence to view as a {@code List} of
748 * characters
749 * @return an {@code List<Character>} view of the character sequence
750 * @since 7.0
751 */
752 @Beta public static List<Character> charactersOf(CharSequence sequence) {
753 return new CharSequenceAsList(checkNotNull(sequence));
754 }
755
756 private static final class CharSequenceAsList
757 extends AbstractList<Character> {
758 private final CharSequence sequence;
759
760 CharSequenceAsList(CharSequence sequence) {
761 this.sequence = sequence;
762 }
763
764 @Override public Character get(int index) {
765 checkElementIndex(index, size()); // for GWT
766 return sequence.charAt(index);
767 }
768
769 @Override public int size() {
770 return sequence.length();
771 }
772 }
773
774 /**
775 * Returns a reversed view of the specified list. For example, {@code
776 * Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3,
777 * 2, 1}. The returned list is backed by this list, so changes in the returned
778 * list are reflected in this list, and vice-versa. The returned list supports
779 * all of the optional list operations supported by this list.
780 *
781 * <p>The returned list is random-access if the specified list is random
782 * access.
783 *
784 * @since 7.0
785 */
786 public static <T> List<T> reverse(List<T> list) {
787 if (list instanceof ImmutableList) {
788 return ((ImmutableList<T>) list).reverse();
789 } else if (list instanceof ReverseList) {
790 return ((ReverseList<T>) list).getForwardList();
791 } else if (list instanceof RandomAccess) {
792 return new RandomAccessReverseList<T>(list);
793 } else {
794 return new ReverseList<T>(list);
795 }
796 }
797
798 private static class ReverseList<T> extends AbstractList<T> {
799 private final List<T> forwardList;
800
801 ReverseList(List<T> forwardList) {
802 this.forwardList = checkNotNull(forwardList);
803 }
804
805 List<T> getForwardList() {
806 return forwardList;
807 }
808
809 private int reverseIndex(int index) {
810 int size = size();
811 checkElementIndex(index, size);
812 return (size - 1) - index;
813 }
814
815 private int reversePosition(int index) {
816 int size = size();
817 checkPositionIndex(index, size);
818 return size - index;
819 }
820
821 @Override public void add(int index, @Nullable T element) {
822 forwardList.add(reversePosition(index), element);
823 }
824
825 @Override public void clear() {
826 forwardList.clear();
827 }
828
829 @Override public T remove(int index) {
830 return forwardList.remove(reverseIndex(index));
831 }
832
833 @Override protected void removeRange(int fromIndex, int toIndex) {
834 subList(fromIndex, toIndex).clear();
835 }
836
837 @Override public T set(int index, @Nullable T element) {
838 return forwardList.set(reverseIndex(index), element);
839 }
840
841 @Override public T get(int index) {
842 return forwardList.get(reverseIndex(index));
843 }
844
845 @Override public int size() {
846 return forwardList.size();
847 }
848
849 @Override public List<T> subList(int fromIndex, int toIndex) {
850 checkPositionIndexes(fromIndex, toIndex, size());
851 return reverse(forwardList.subList(
852 reversePosition(toIndex), reversePosition(fromIndex)));
853 }
854
855 @Override public Iterator<T> iterator() {
856 return listIterator();
857 }
858
859 @Override public ListIterator<T> listIterator(int index) {
860 int start = reversePosition(index);
861 final ListIterator<T> forwardIterator = forwardList.listIterator(start);
862 return new ListIterator<T>() {
863
864 boolean canRemoveOrSet;
865
866 @Override public void add(T e) {
867 forwardIterator.add(e);
868 forwardIterator.previous();
869 canRemoveOrSet = false;
870 }
871
872 @Override public boolean hasNext() {
873 return forwardIterator.hasPrevious();
874 }
875
876 @Override public boolean hasPrevious() {
877 return forwardIterator.hasNext();
878 }
879
880 @Override public T next() {
881 if (!hasNext()) {
882 throw new NoSuchElementException();
883 }
884 canRemoveOrSet = true;
885 return forwardIterator.previous();
886 }
887
888 @Override public int nextIndex() {
889 return reversePosition(forwardIterator.nextIndex());
890 }
891
892 @Override public T previous() {
893 if (!hasPrevious()) {
894 throw new NoSuchElementException();
895 }
896 canRemoveOrSet = true;
897 return forwardIterator.next();
898 }
899
900 @Override public int previousIndex() {
901 return nextIndex() - 1;
902 }
903
904 @Override public void remove() {
905 checkRemove(canRemoveOrSet);
906 forwardIterator.remove();
907 canRemoveOrSet = false;
908 }
909
910 @Override public void set(T e) {
911 checkState(canRemoveOrSet);
912 forwardIterator.set(e);
913 }
914 };
915 }
916 }
917
918 private static class RandomAccessReverseList<T> extends ReverseList<T>
919 implements RandomAccess {
920 RandomAccessReverseList(List<T> forwardList) {
921 super(forwardList);
922 }
923 }
924
925 /**
926 * An implementation of {@link List#hashCode()}.
927 */
928 static int hashCodeImpl(List<?> list) {
929 // TODO(user): worth optimizing for RandomAccess?
930 int hashCode = 1;
931 for (Object o : list) {
932 hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
933
934 hashCode = ~~hashCode;
935 // needed to deal with GWT integer overflow
936 }
937 return hashCode;
938 }
939
940 /**
941 * An implementation of {@link List#equals(Object)}.
942 */
943 static boolean equalsImpl(List<?> list, @Nullable Object object) {
944 if (object == checkNotNull(list)) {
945 return true;
946 }
947 if (!(object instanceof List)) {
948 return false;
949 }
950
951 List<?> o = (List<?>) object;
952
953 return list.size() == o.size()
954 && Iterators.elementsEqual(list.iterator(), o.iterator());
955 }
956
957 /**
958 * An implementation of {@link List#addAll(int, Collection)}.
959 */
960 static <E> boolean addAllImpl(
961 List<E> list, int index, Iterable<? extends E> elements) {
962 boolean changed = false;
963 ListIterator<E> listIterator = list.listIterator(index);
964 for (E e : elements) {
965 listIterator.add(e);
966 changed = true;
967 }
968 return changed;
969 }
970
971 /**
972 * An implementation of {@link List#indexOf(Object)}.
973 */
974 static int indexOfImpl(List<?> list, @Nullable Object element) {
975 ListIterator<?> listIterator = list.listIterator();
976 while (listIterator.hasNext()) {
977 if (Objects.equal(element, listIterator.next())) {
978 return listIterator.previousIndex();
979 }
980 }
981 return -1;
982 }
983
984 /**
985 * An implementation of {@link List#lastIndexOf(Object)}.
986 */
987 static int lastIndexOfImpl(List<?> list, @Nullable Object element) {
988 ListIterator<?> listIterator = list.listIterator(list.size());
989 while (listIterator.hasPrevious()) {
990 if (Objects.equal(element, listIterator.previous())) {
991 return listIterator.nextIndex();
992 }
993 }
994 return -1;
995 }
996
997 /**
998 * Returns an implementation of {@link List#listIterator(int)}.
999 */
1000 static <E> ListIterator<E> listIteratorImpl(List<E> list, int index) {
1001 return new AbstractListWrapper<E>(list).listIterator(index);
1002 }
1003
1004 /**
1005 * An implementation of {@link List#subList(int, int)}.
1006 */
1007 static <E> List<E> subListImpl(
1008 final List<E> list, int fromIndex, int toIndex) {
1009 List<E> wrapper;
1010 if (list instanceof RandomAccess) {
1011 wrapper = new RandomAccessListWrapper<E>(list) {
1012 @Override public ListIterator<E> listIterator(int index) {
1013 return backingList.listIterator(index);
1014 }
1015
1016 private static final long serialVersionUID = 0;
1017 };
1018 } else {
1019 wrapper = new AbstractListWrapper<E>(list) {
1020 @Override public ListIterator<E> listIterator(int index) {
1021 return backingList.listIterator(index);
1022 }
1023
1024 private static final long serialVersionUID = 0;
1025 };
1026 }
1027 return wrapper.subList(fromIndex, toIndex);
1028 }
1029
1030 private static class AbstractListWrapper<E> extends AbstractList<E> {
1031 final List<E> backingList;
1032
1033 AbstractListWrapper(List<E> backingList) {
1034 this.backingList = checkNotNull(backingList);
1035 }
1036
1037 @Override public void add(int index, E element) {
1038 backingList.add(index, element);
1039 }
1040
1041 @Override public boolean addAll(int index, Collection<? extends E> c) {
1042 return backingList.addAll(index, c);
1043 }
1044
1045 @Override public E get(int index) {
1046 return backingList.get(index);
1047 }
1048
1049 @Override public E remove(int index) {
1050 return backingList.remove(index);
1051 }
1052
1053 @Override public E set(int index, E element) {
1054 return backingList.set(index, element);
1055 }
1056
1057 @Override public boolean contains(Object o) {
1058 return backingList.contains(o);
1059 }
1060
1061 @Override public int size() {
1062 return backingList.size();
1063 }
1064 }
1065
1066 private static class RandomAccessListWrapper<E>
1067 extends AbstractListWrapper<E> implements RandomAccess {
1068 RandomAccessListWrapper(List<E> backingList) {
1069 super(backingList);
1070 }
1071 }
1072
1073 /**
1074 * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
1075 */
1076 static <T> List<T> cast(Iterable<T> iterable) {
1077 return (List<T>) iterable;
1078 }
1079 }